package spring_user;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DateUtil {

	private static Log log = LogFactory.getLog(DateUtil.class);

	private static String defaultDatePattern = "yyyy-MM-dd HH:mm:ss";

	private static String datePattern = "yyyyMMdd";

	public static final int START_DATE = 1;

	public static final int END_DATE = 2;

	private static String timePattern = "HH:mm";
	
	private static String timePattern2 = "HH:mm:ss";

	public static Date getFirstDayOfMonth(Date date) {
		return getCalendarDate(START_DATE, date, true);
	}

	public static Date getLastDayOfMonth(Date date) {
		return getCalendarDate(END_DATE, date, true);
	}

	/**
	 * 取得日程管理查询日期 for spp
	 * 
	 * @param type
	 * @param date
	 * @param tuncate
	 * @return
	 */
	private static Date getCalendarDate(int type, Date date, boolean truncate) {
		Calendar rightNow = Calendar.getInstance(Locale.CHINA);
		rightNow.setTime(date);
		int base = 1;
		switch (type) {
		case END_DATE:
			base = 0;
			rightNow.add(Calendar.MONTH, 1);
			if (!truncate) {
				break;
			}
		case START_DATE:
			rightNow.add(Calendar.DAY_OF_MONTH, base
					- rightNow.get(Calendar.DAY_OF_MONTH));
			break;
		default:
			break;
		}
		return rightNow.getTime();
	}

	/**
	 * Return default datePattern (MM/dd/yyyy)
	 * 
	 * @return a string representing the date pattern on the UI
	 */
	public static String getDefaultDatePattern() {

		return defaultDatePattern;
	}

	public static String getDatePattern() {
		return datePattern;
	}

	/**
	 * This method attempts to convert an Oracle-formatted date in the form
	 * dd-MMM-yyyy to mm/dd/yyyy.
	 * 
	 * @param aDate
	 *            date from database as a string
	 * @return formatted string for the ui
	 */
	public static final String getDate(Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate != null) {
			df = new SimpleDateFormat(getDefaultDatePattern());
			returnValue = df.format(aDate);
		}

		return (returnValue);
	}

	public static final String getDate_yyyyMMdd(Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate != null) {
			df = new SimpleDateFormat(getDatePattern());
			returnValue = df.format(aDate);
		}

		return (returnValue);
	}

	/**
	 * This method generates a string representation of a date/time in the
	 * format you specify on input
	 * 
	 * @param aMask
	 *            the date pattern the string is in
	 * @param strDate
	 *            a string representation of a date
	 * @return a converted Date object
	 * @see java.text.SimpleDateFormat
	 * @throws ParseException
	 */
	public static final Date convertStringToDate(String aMask, String strDate)
			throws ParseException {
		SimpleDateFormat df = null;
		Date date = null;
		df = new SimpleDateFormat(aMask);

		if (log.isDebugEnabled()) {
			log.debug("converting '" + strDate + "' to date with mask '"
					+ aMask + "'");
		}

		try {
			date = df.parse(strDate);
		} catch (ParseException pe) {
			throw new ParseException(pe.getMessage(), pe.getErrorOffset());
		}

		return (date);
	}

	/**
	 * 
	 * @param date
	 * @return
	 */
	public static final java.sql.Date convertUtilDateToSqlDate(
			java.util.Date date) {
		java.sql.Date current = new java.sql.Date(date.getTime());
		return current;

	}

	/**
	 * This method returns the current date time in the format: MM/dd/yyyy HH:MM
	 * a
	 * 
	 * @param theTime
	 *            the current time
	 * @return the current date/time
	 */
	public static String getTimeNow(Date theTime) {
		return getDateTime(timePattern, theTime);
	}
	//
	public static String getHMS(Date theTime) {
		return getDateTime(timePattern2, theTime);
	}

	/**
	 * This method returns the current date in the format: MM/dd/yyyy
	 * 
	 * @return the current date
	 * @throws ParseException
	 */
	public static Calendar getToday() throws ParseException {
		Date today = new Date();
		SimpleDateFormat df = new SimpleDateFormat(getDefaultDatePattern());
		String todayAsString = df.format(today);
		Calendar cal = new GregorianCalendar();
		cal.setTime(convertStringToDate(todayAsString));

		return cal;
	}

	/**
	 * This method generates a string representation of a date's date/time in
	 * the format you specify on input
	 * 
	 * @param aMask
	 *            the date pattern the string is in
	 * @param aDate
	 *            a date object
	 * @return a formatted string representation of the date
	 * 
	 * @see java.text.SimpleDateFormat
	 */
	public static final String getDateTime(String aMask, Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate == null) {
			log.error("aDate is null!");
		} else {
			df = new SimpleDateFormat(aMask);
			returnValue = df.format(aDate);
		}

		return (returnValue);
	}

	/**
	 * This method generates a string representation of a date based on the
	 * System Property 'dateFormat' in the format you specify on input
	 * 
	 * @param aDate
	 *            A date to convert
	 * @return a string representation of the date
	 */
	public static final String convertDateToString(Date aDate) {
		return getDateTime(getDefaultDatePattern(), aDate);
	}

	/**
	 * This method converts a String to a date using the datePattern
	 * 
	 * @param strDate
	 *            the date to convert (in format yyyy-mm-dd)
	 * @return a date object
	 * 
	 * @throws ParseException
	 */
	public static Date convertStringToDate(String strDate)
			throws ParseException {
		Date aDate = null;

		try {
			if (log.isDebugEnabled()) {
				log.debug("converting date with pattern: "
						+ getDefaultDatePattern());
			}

			aDate = convertStringToDate(getDefaultDatePattern(), strDate);
		} catch (ParseException pe) {
			log.error("Could not convert '" + strDate
					+ "' to a date, throwing exception");
			pe.printStackTrace();
			throw new ParseException(pe.getMessage(), pe.getErrorOffset());

		}

		return aDate;
	}

	private static final SimpleDateFormat mFormat8chars = new SimpleDateFormat(
			"yyyyMMdd");

	private static final SimpleDateFormat mFormatIso8601Day = new SimpleDateFormat(
			"yyyy-MM-dd");

	private static final SimpleDateFormat mFormatZh = new SimpleDateFormat(
			"yyyy年MM月dd日");

	private static final SimpleDateFormat mFormatIso8601 = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ssZ");

	private static final SimpleDateFormat mFormatRfc822 = new SimpleDateFormat(
			"EEE, d MMM yyyy HH:mm:ss z");

	/**
	 * Returns a string the represents the passed-in date parsed according to
	 * the passed-in format. Returns an empty string if the date or the format
	 * is null.
	 */
	public static String format(Date aDate, SimpleDateFormat aFormat) {
		if (aDate == null || aFormat == null) {
			return "";
		}
		return aFormat.format(aDate);
	}

	public static String format(Date aDate, String aFormat) {
		if (aDate == null || aFormat == null) {
			return "";
		}
		return new SimpleDateFormat(aFormat).format(aDate);
	}

	public static String getDefaultDateFormat(Date aDate) {

		return DateUtil.format(aDate, mFormatIso8601Day);
	}

	public static String getTimeFormat(Date aDate) {

		return DateUtil.format(aDate, mFormatIso8601);
	}

	/**
	 * 获取中文格式的日期格式2007年11月08日
	 * 
	 * @param data
	 * @return
	 */
	public static String getZhTimeFormat(Date data) {

		return DateUtil.format(data, mFormatZh);

	}

	public static String getDefaultDateFormat(long aDate) {
		Date date = new Date();
		date.setTime(aDate);

		return DateUtil.format(date, mFormatIso8601Day);
	}

	/**
	 * 2007-11-07 按照需要获得符合"number值"日后的日期
	 * 
	 * @param number
	 * @return
	 */
	public static String getDateofneed(int number) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date myDate = new java.util.Date();
		long myTime = (myDate.getTime() / 1000) + 60 * 60 * 24 * number;
		myDate.setTime(myTime * 1000);
		String needDate = formatter.format(myDate);
		return needDate;
	}

	public static String getYear(Date date) {
		String currentTime = DateUtil.getDefaultDateFormat(date.getTime());
		String year = currentTime.substring(0, 4);
		// String month = currentTime.substring(5, 7);
		return year;

	}

	public static String getMonth(Date date) {
		String currentTime = DateUtil.getDefaultDateFormat(date.getTime());
		String month = currentTime.substring(5, 7);
		return month;

	}

	public static String getDay(Date date) {
		String currentTime = DateUtil.getDefaultDateFormat(date.getTime());
		String day = currentTime.substring(8, 10);
		return day;

	}

	/**
	 * 根据日期生成附件上传目录结构 2008\\09\\
	 * 
	 * @param date
	 * @return
	 */
	public static String getDirectoryByDate(Date date) {
		return getYear(date) + File.separator + getMonth(date) + File.separator;

	}

	/**
	 * 根据日期生成附件上传目录结构，精确到天 2008\\09\\10
	 * 
	 * @param date
	 * @return
	 */
	public static String getDirectoryByDateWithDay(Date date) {
		return getYear(date) + "/" + getMonth(date) + "/" + getDay(date);
	}

	/**
	 * 根据日期获取访问url（相对于路径）
	 * 
	 * @param date
	 * @return
	 */
	public static String getUrlByDate(Date date) {
		return getYear(date) + "/" + getMonth(date) + "/";

	}

	/**
	 * 给date添加(days,hours,minutes , seconds)时间偏移
	 * 
	 * @param date
	 *            //时间基准
	 * @param days
	 *            //偏移的天数
	 * @param hours
	 *            //偏移的小时
	 * @param minutes
	 *            //偏移的分钟
	 * @param seconds
	 *            //偏移的秒数
	 * @return Date //返回偏移后的日期
	 * @author tzc 2005-09-21 )
	 */
	public static synchronized Date Add(Date date, int days, int hours,
			int minutes, int seconds) {

		Date dt = date;
		if (dt != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(dt);

			if (days != 0) {
				calendar.add(Calendar.DATE, days);
			}
			if (hours != 0) {
				calendar.add(Calendar.HOUR, hours);
			}
			if (minutes != 0) {
				calendar.add(Calendar.MINUTE, minutes);
			}
			if (seconds != 0) {
				calendar.add(Calendar.SECOND, seconds);
			}
			dt = calendar.getTime();
		}
		return dt;
	}

	/**
	 * 获取当前年
	 * 
	 * @return
	 */
	public static int getCurrentYear() {
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.YEAR);

	}

	/**
	 * 取得判断日期是否是星期二或者星期五,如果不是则取的下一个星期二星期五的日期
	 * 
	 * @param date
	 *            //需要判断的日期
	 * @return Date //返回判断结果的日期
	 */
	public static Date getNextTuesDayOrFriday(Date date) {
		if (date != null) {
			do {
				date = Add(date, 1, 0, 0, 0);
			} while (date.getDay() != 2 && date.getDay() != 5);
		}

		return date;
	}

	public static String getTimePattern() {
		return timePattern;
	}

	public static Long getMillisByDate(String date) {
		Calendar nowTime = new GregorianCalendar();
		DateFormat format = DateFormat.getDateInstance();
		Date temp2 = null;
		try {
			temp2 = format.parse(date);
			// System.out.println(temp2);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		nowTime.setTime(temp2);
		return nowTime.getTimeInMillis();
	}

	public static Long getMillisByDate(Date date) {
		Calendar nowTime = new GregorianCalendar();

		nowTime.setTime(date);
		return nowTime.getTimeInMillis();
	}

	// 获取指定时间小时数
	public static String getHourByDate(Date date) {
		return getTimeNow(date).substring(0, 2);
	}

	// 查看今天是本年第几周
	public static int getThisWeek() throws Exception {
		try {
			java.util.Calendar calendar = new java.util.GregorianCalendar();
			int thisWeek = calendar.get(Calendar.WEEK_OF_YEAR);
			return thisWeek;
		} catch (Exception e) {
			throw new Exception(e.toString());
		}
	}

	// 取前一天的日期
	public static Date getYesterdayCurrentDate() {
		long millis = System.currentTimeMillis();
		millis = millis - 24 * 60 * 60 * 1000;
		Date date = new Date(millis);
		return date;
	}

	/**
	 * 比较两个日期并返回两个日期相差多少天(d1－d2)
	 * 
	 * @param d1
	 *            Date
	 * @param d2
	 *            Date
	 * @return int
	 */
	public static int compareDateOnDay(Date d1, Date d2) {
		if (d1.getTime() == d2.getTime()) {
			return 0; // 日期相同返回0
		}
		int flag = -1;
		// 比较两个日期使日期较小的日期排在前面
		if (d1.getTime() > d2.getTime()) { // 日期一在日期二之后
			Date temp = d1;
			d1 = d2;
			d2 = temp;
			flag = 1;
		}
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(d1);
		c2.setTime(d2);
		int y1 = c1.get(Calendar.YEAR);
		int y2 = c2.get(Calendar.YEAR);
		int day1 = c1.get(Calendar.DAY_OF_YEAR);
		int day2 = c2.get(Calendar.DAY_OF_YEAR);
		int days = 0;
		for (int i = 1; i <= y2 - y1; i++) {
			days += getYearDays(y1);
		}
		return (days - day1 + day2) * flag;
	}

	/**
	 * 输入日期与今相差多少(日,时,分,秒)
	 * 
	 * @param d1
	 * @return
	 */
	public static String compareDate(Date d1) {
		Date d2 = new Date();
		if (d1.getTime() == d2.getTime())
			return "0分钟"; // 日期相同返回0

		d2 = new Date(d2.getTime() - d1.getTime());

		long hm = d2.getTime();
		long day = hm / (24 * 60 * 60 * 1000);
		long hour = hm % (24 * 60 * 60 * 1000) / (60 * 60 * 1000);
		long minute = ((hm % (24 * 60 * 60 * 1000)) % (60 * 60 * 1000))
				/ (60 * 1000);
		long second = (((hm % (24 * 60 * 60 * 1000)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000;

		String rets = "";
		if (day != 0)
			rets += day + "天";
		if (hour != 0)
			rets += hour + "小时";
		if (minute != 0)
			rets += minute + "分";
		if (second != 0)
			rets += second + "秒";

		return rets;
	}

	/**
	 * 判断闰年的方法
	 * 
	 * @param year
	 *            int 年份
	 * @return boolean（true=闰年，false=非闰年）
	 */
	public static boolean isLeapYear(int year) {
		if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
			return true;
		}
		return false;
	}
	
	
	
	// 秒转换成两位的时间，格式：HH:mm:ss
	public static String turnSecondsToTimestring(int seconds) {
		String result = "";
		int hour = 0, min = 0, second = 0;
		hour = seconds / 3600;
		min = (seconds - hour * 3600) / 60;
		second = seconds - hour * 3600 - min * 60;
		if (hour < 10) {
			result += "0" + hour + ":";
		} else {
			result += hour + ":";
		}
		if (min < 10) {
			result += "0" + min + ":";
		} else {
			result += min + ":";
		}
		if (second < 10) {
			result += "0" + second;
		} else {
			result += second;
		}

		return result;

	}

	

	/**
	 * 得到一年的天数的方法
	 * 
	 * @param year
	 *            int 年份
	 * @return int （非闰年=365，闰年=366）
	 */
	public static int getYearDays(int year) {
		if (isLeapYear(year)) {
			return 366;
		}
		return 365;
	}

	public static void main(String[] args){
		//System.out.println(DateUtil.convertDateToString(new Date()));
		//System.out.println(DateUtil.getTimeNow(new Date()));
		//System.out.println(DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss",new Date()));
		//System.out.println(DateUtil.getZhTimeFormat(new Date()));
		//System.out.println(DateUtil.getHMS(new Date()));
		//System.out.println(DateUtil.Add(new Date(),1,0,0,0));
		System.out.println(DateUtil.getMillisByDate(new Date()));
	}
}
